#include "searchManager.h"
#include <QDesktopServices>
#include <QUrl>
#include <QFileInfo>
#include <QDebug>
#include <QMessageBox>
#include <QTimer>
#include <QPushButton>

/**
 * 搜索，调用bing
 * @brief SearchManager::searchOnline
 * @param item
 */

void SearchManager::searchOnline(const ClipboardItem& item) {
    // 根据 ClipboardItem 类型执行对应的操作
    if (item.getType() == ClipboardType::Text) {
        QString text = item.getContent().toString();
        QUrl bingSearchUrl = QUrl("https://www.bing.com/search?q=" + QUrl::toPercentEncoding(text));
        QDesktopServices::openUrl(bingSearchUrl);
        qDebug() << "Searching text on Bing:" << text;
    }
    else if (item.getType() == ClipboardType::Url) {
        QString urlText = item.getContent().toString();
        QUrl url(urlText);
        if (url.isValid()) {
            QDesktopServices::openUrl(url);
            qDebug() << "Opening URL in browser:" << urlText;
        } else {
            qDebug() << "Invalid URL:" << urlText;
        }
    }
    else {
        qDebug() << "The item type is not supported for online search.";
    }
}


void SearchManager::askToSearch(const ClipboardItem& item) {
    QMessageBox msgBox;
    msgBox.setWindowTitle("打开 URL");
    msgBox.setText("您复制的内容是一个网页链接，是否要打开它？");
    QPushButton *noButton = msgBox.addButton(QMessageBox::No);
    msgBox.addButton(QMessageBox::Yes);

    // 设置对话框始终在最前面
    msgBox.setWindowFlags(msgBox.windowFlags() | Qt::WindowStaysOnTopHint);

    // 设置一个倒计时器
    int countdownTime = 5; // 5秒
    QTimer *timer = new QTimer(&msgBox);
    timer->setInterval(1000); // 每秒更新一次倒计时
    timer->start();

    // 更新 "No" 按钮的文本
    QObject::connect(timer, &QTimer::timeout, [&]() {
        countdownTime--;
        noButton->setText(QString("No (%1s)").arg(countdownTime));
        if (countdownTime <= 0) {
            timer->stop();
            msgBox.close();  // 5秒后自动关闭对话框
        }
    });

    // 执行对话框并等待用户选择
    int btn = msgBox.exec();

    if (btn == QMessageBox::Yes) {
        // 用户选择“是”，打开 URL
        SearchManager::searchOnline(item);
    }
}
